import 'dart:convert';

import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:azlistview/azlistview.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:ost_flutter_module/class/entity/store/store_region_entity.dart';
import 'package:ost_flutter_module/class/store/city_page/bloc/city_page_bloc.dart';
import 'package:ost_flutter_module/common/adapt.dart';
import 'package:ost_flutter_module/common/color.dart';
import 'package:ost_flutter_module/common/styles.dart';
import 'package:ost_flutter_module/common/utils.dart';
import 'package:ost_flutter_module/widget/custom_widget/custom_search_app_bar.dart';
import 'package:ost_flutter_module/widget/custom_widget/custome_divider.dart';
import 'package:ost_flutter_module/widget/custom_widget/custome_size_icon_button.dart';
import 'package:ost_flutter_module/widget/custom_widget/image_text_button.dart';
import 'package:ost_flutter_module/widget/dialog/tips_dialog.dart';
import 'package:ost_flutter_module/widget/loading/loading_empty_widget.dart';
import 'package:ost_flutter_module/widget/loading/loading_error_widget.dart';
import 'package:ost_flutter_module/widget/loading/loading_view.dart';
import 'package:ost_flutter_module/widget/loading/loading_widget.dart';
import 'package:sp_util/sp_util.dart';

class StoreCityPage extends StatelessWidget {
  const StoreCityPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => CityPageBloc()..add(CityPageFetchData()),
      child: _CityPageBody(),
    );
  }
}

class _CityPageBody extends StatefulWidget {
  _CityPageBody({Key key}) : super(key: key);

  @override
  __CityPageBodyState createState() => __CityPageBodyState();
}

class __CityPageBodyState extends State<_CityPageBody> {
  List<CityModel> cityList;
  List<CityModel> historyCityList;
  String imgFavorite;
  String keyword;

  @override
  void initState() {
    super.initState();
    cityList = [];
    historyCityList = [];
    imgFavorite = Utils.getImgPath('ic_favorite');
    keyword = '';

    // 定位城市
    historyCityList.add(CityModel(city: '深圳', isLoc: true));
    var _selectedList =
        SpUtil.getObjList(SpUtilKey.historyList, (v) => CityModel.fromJson(v));
    historyCityList.addAll(_selectedList);
  }

  _loadData(List<StoreRegionEntity> list) {
    Future(() {
      if (cityList.isNotEmpty) cityList.clear();

      if (list.isEmpty) return;

      for (int i = 0; i < list.length; i++) {
        var province = list[i];
        var citys = province.citys;
        for (var city in citys) {
          var cityModel =
              CityModel(pid: city.pid, cid: city.cid, city: city.city);
          cityList.add(cityModel);
        }
      }
    }).then((_) {
      _handleList(cityList);
    });
  }

  _handleList(List<CityModel> list) async {
    if (list == null || list.isEmpty) return;
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin = PinyinHelper.getPinyinE(list[i].city);
      String tag = pinyin.substring(0, 1).toUpperCase();
      list[i].pinyin = pinyin;
      if (RegExp('[A-Z]').hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = '#';
      }
    }
    SuspensionUtil.sortListBySuspensionTag(list);
    SuspensionUtil.setShowSuspensionStatus(cityList);
    // add header.
    cityList.insert(0, CityModel(tagIndex: imgFavorite));
  }

  pop(CityModel model) {
    Future(() {
      // 存储选中的城市，添加进 historyList
      List<CityModel> _selectedList = [];

      _selectedList = SpUtil.getObjList<CityModel>(SpUtilKey.historyList, (v) {
        return CityModel.fromJson(v as Map<String, dynamic>);
      });
      var _nameList = []; //_selectedList.map((e) => e.cid);
      for (var item in _selectedList) {
        _nameList.add('${item.pid}-${item.cid}');
      }
      if (!_nameList.contains('${model.pid}-${model.cid}')) {
        _selectedList.add(model);
      }
      SpUtil.putObjectList(SpUtilKey.historyList, _selectedList);
    }).then((value) {
      Navigator.pop(context, model);
    });
  }

  _search(BuildContext context, {String keyword = '', bool isClear}) {
    if (isClear) {
      keyword = keyword;
      setState(() {});
    } else {
      if (keyword.isNotEmpty) {
        keyword = keyword;
        setState(() {});
      }
    }
  }

  Widget getSusItem(BuildContext context, String tag, {double susHeight = 40}) {
    return Container(
      height: susHeight,
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.only(left: Adapt.px(10)),
      color: colorFAFAFA,
      alignment: Alignment.centerLeft,
      child: Text(
        '$tag',
        softWrap: false,
        style: TextStyle(
          fontSize: 14.0,
          color: Color(0xFF666666),
        ),
      ),
    );
  }

  Widget getListItem(BuildContext context, CityModel model,
      {double susHeight = 44}) {
    return Ink(
      child: Material(
        color: Colors.white,
        child: InkWell(
          child: Padding(
            padding: EdgeInsets.only(left: Adapt.px(10)),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                    height: Adapt.px(44),
                    alignment: Alignment.centerLeft,
                    child: Text(model.city, style: TextStyles.titleStyle)),
                GDivider(indent: 0, endIndent: 30),
              ],
            ),
          ),
          onTap: () {
            pop(model);
          },
        ),
      ),
    );
  }

  Widget _buildHeader(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(
        top: Adapt.px(10),
        left: Adapt.px(10),
        bottom: Adapt.px(10),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
            Text("定位城市/最近访问", style: TextStyles.detailTitleStyle),
            GIconButton(
              svg: Utils.svgAssets('icon_del'),
              onPressed: () async {
                OkCancelResult tag = await showOkCancelAlertDialog(
                  context: context,
                  title: '提示',
                  message: '确定删除最近访问城市吗？',
                  okLabel: '确定',
                  cancelLabel: '取消',
                );

                if (tag == OkCancelResult.ok) {
                  SpUtil.putObjectList(SpUtilKey.historyList, []);
                  setState(() {
                    historyCityList.removeWhere(
                        (element) => historyCityList.indexOf(element) != 0);
                  });
                }
              },
            ),
          ]),
          SizedBox(height: Adapt.px(4)),
          Wrap(
            spacing: Adapt.px(10),
            runSpacing: Adapt.px(10),
            children: historyCityList.map((model) {
              return GImageTextButton(
                model.city,
                svg: (model.isLoc != null && model.isLoc == true)
                    ? Utils.svgAssets('icon_location_yellow')
                    : null,
                padding: 10,
                textLeadingPadding: 2,
                mainAxisSize: MainAxisSize.min,
                onTap: (value) {
                  pop(model);
                },
              );
            }).toList(),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<CityPageBloc, CityPageState>(
      builder: (context, state) {
        var _dataModel = context.read<CityPageBloc>().dataModel;

        return Scaffold(
          appBar: AppBar(
            automaticallyImplyLeading: false,
            backgroundColor: colorFAFAFA,
            elevation: 0,
            title: GSearchAppBar(
              hintText: '城市名',
              onChanged: (value) {},
              onClear: () => _search(context, isClear: true),
              onSearch: (value) =>
                  _search(context, keyword: value, isClear: false),
              onCancel: () {
                Navigator.pop(context);
              },
            ),
          ),
          body: LoadingView(
            status: _dataModel?.loadingStatus,
            loadingContent: LoadingWidget(),
            errorContent: LoadingErrorWidget(
                errorTitle: _dataModel?.errorMsg,
                onRetry: () => context
                    .read<CityPageBloc>()
                    .add(CityPageFetchData(action: null))),
            successContent: _buildBody(context, list: _dataModel.dataList),
            emptyContent: LoadingEmptyWidget(),
          ),
        );
      },
    );
  }

  _buildBody(BuildContext context, {List list}) {
    return FutureBuilder(
      future: _loadData(list),
      builder: (ct, snap) {
        if (snap.hasError) return Container();

        return SafeArea(
          bottom: true,
          child: AzListView(
            data: cityList,
            itemCount: cityList.length,
            itemBuilder: (BuildContext context, int index) {
              // String tag = cityList[index].getSuspensionTag();
              // if (imgFavorite == tag) return _buildHeader(context);
              if (index == 0) return _buildHeader(context);
              return getListItem(context, cityList[index]);
            },
            susItemBuilder: (BuildContext context, int index) {
              String tag = cityList[index].getSuspensionTag();
              if (imgFavorite == tag) return Container();
              return getSusItem(context, tag);
            },
            indexBarData: SuspensionUtil.getTagIndexList(cityList),
            indexBarOptions: IndexBarOptions(localImages: [imgFavorite]),
          ),
        );
      },
    );
  }
}

class CityModel extends ISuspensionBean {
  num pid;
  num cid;
  String city;
  String tagIndex;
  String pinyin;
  bool isLoc;

  CityModel({
    this.cid,
    this.pid,
    this.city,
    this.tagIndex,
    this.pinyin,
    this.isLoc,
  });

  CityModel.fromJson(Map<String, dynamic> json) {
    cid = json['cid'];
    pid = json['pid'];
    city = json['city']?.toString();
    tagIndex = json['tagIndex']?.toString();
    pinyin = json['pinyin']?.toString();
    isLoc = json['isLoc'];
  }

  Map<String, dynamic> toJson() => {
        'cid': cid,
        'pid': pid,
        'city': city,
        'tagIndex': tagIndex,
        'pinyin': pinyin,
        'isLoc': isLoc,
      };

  @override
  String getSuspensionTag() => tagIndex;
}
